package dianmobile.eistarandroid.ui.activities;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import dianmobile.eistarandroid.ByhhAndroidApplication;
import dianmobile.eistarandroid.R;
import dianmobile.eistarandroid.beans.BoardItemEntity;
import dianmobile.eistarandroid.network.request.RequestCallback;
import dianmobile.eistarandroid.network.request.SubBoardRequest;
import dianmobile.eistarandroid.ui.Adapter.BoardListAdapter;
import dianmobile.eistarandroid.ui.views.SwipeActivity;
import dianmobile.eistarandroid.utils.ConstantsData;
import zrc.widget.SimpleHeader;
import zrc.widget.ZrcListView;

public class BoardListActivity extends SwipeActivity{

    private EditText edtSearchInput;
    private TextView tvTitle;
    private ImageButton btnSearch;
    private BoardListAdapter boardListAdapter;
    private List<BoardItemEntity> boardItemList = new ArrayList<>();
    private ZrcListView boardListView;

    private List<BoardItemEntity> bookBoardList;

    /** indicate the sub board belongs to which group */
    private String groupName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ByhhAndroidApplication application = (ByhhAndroidApplication)getApplication();
        application.getActivityList().add(this);

        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_board_list);
        Intent intent = getIntent();
        groupName = intent.getStringExtra("groupName");

        application = (ByhhAndroidApplication)getApplication();
        bookBoardList = application.getSubscriptionList();

        boardListView = (ZrcListView) findViewById(R.id.lv_board_list);
        setPullToRefresh();
        boardListAdapter = new BoardListAdapter(this, boardItemList);
        boardListView.setAdapter(boardListAdapter);
        boardListView.refresh();
//        downloadData(groupName);

        boardListView.setOnItemClickListener(new zrc.widget.ZrcListView.OnItemClickListener() {
            @Override
            public void onItemClick(ZrcListView parent, View view, int position, long id) {
                BoardItemEntity item = boardItemList.get(position);
                Intent intent = new Intent(BoardListActivity.this, BoardContentActivity.class);
                intent.putExtra(ConstantsData.EXTRA_BOARD_NAME, item.getBoardName());
                startActivity(intent);
            }
        });

        TitleClickListener titleClickListener = new TitleClickListener();
        ImageButton btnBack = (ImageButton)findViewById(R.id.btn_show_slideMenu);
        btnBack.setImageResource(R.drawable.ic_arrow_back);
        btnBack.setOnClickListener(titleClickListener);
        tvTitle = (TextView)findViewById(R.id.tv_title_mainActivity);
        tvTitle.setText(groupName);
        btnSearch = (ImageButton)findViewById(R.id.btn_right_button);
        btnSearch.setOnClickListener(titleClickListener);
        edtSearchInput = (EditText)findViewById(R.id.edt_search_input);

    }

    @Override
    public void onDestroy() {
        ByhhAndroidApplication application = (ByhhAndroidApplication)getApplication();
        application.getActivityList().remove(this);
        super.onDestroy();
    }

    /**
     * download sub board data from server.
     * @param groupName
     */
    private void downloadData(String groupName) {
        SubBoardRequest.execute(this, new RequestCallback() {
            @Override
            public void onResult(Map<String, Object> result, String error) {
                if (error == null) {
                    List<BoardItemEntity> temp = (List<BoardItemEntity>) result.get("result_data");
                    for (int i = 0; i < bookBoardList.size(); i++) {
                        for ( int j = 0; j < temp.size(); j++) {
                            if (bookBoardList.get(i).getBoardName().equals(temp.get(j).getBoardName())) {
                                temp.get(j).setIsBookmark(true);
                            }
                        }
                    }
                    boardItemList.addAll(temp);
                    boardListAdapter.notifyDataSetChanged();
                    boardListView.setRefreshSuccess();
                } else {
                    boardListView.setRefreshFail("网络错误");
                }
            }
        }, groupName);
    }

    private void setPullToRefresh() {
        SimpleHeader header = new SimpleHeader(this);
        header.setTextColor(0xff0066aa);
        header.setCircleColor(0xff33bbee);
        boardListView.setHeadable(header);

        boardListView.setOnRefreshStartListener(new ZrcListView.OnStartListener() {
            @Override
            public void onStart() {
                downloadData(groupName);
            }
        });
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideKeyboard(v, ev)) {
                hideKeyboard(v.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时则不能隐藏
     *
     * @param v
     * @param event
     * @return
     */
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击EditText的事件，忽略它。
                return false;
            } else {
                return true;
            }
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditText上，和用户用轨迹球选择其他的焦点
        return false;
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     * @param token
     */
    private void hideKeyboard(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    class TitleClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v){
            switch (v.getId()) {
                case R.id.btn_show_slideMenu:
                    BoardListActivity.this.finish();
                    break;
                case R.id.btn_right_button:
                    if (edtSearchInput.isShown()) {
                        edtSearchInput.setVisibility(View.INVISIBLE);
                        tvTitle.setVisibility(View.VISIBLE);
                        btnSearch.setBackgroundResource(R.drawable.ic_search);
                    } else {
                        tvTitle.setVisibility(View.INVISIBLE);
                        edtSearchInput.setVisibility(View.VISIBLE);
                        edtSearchInput.setText("");
                        btnSearch.setBackgroundResource(R.drawable.ic_close);
                    }
                    break;
                default:
                    break;
            }
        }
    }
}
